import { UploadFileInfo} from '@midwayjs/busboy';
import { Inject, Provide } from '@midwayjs/core';
import { uuidv7 } from 'uuidv7';
import { Config } from '../../dto/config';
import minioConfig from '../../config/config';
const config = minioConfig as Config;
import { GetFileExtension } from './originelFileName';
import * as Minio from 'minio';

@Provide()
export class MinioService {
    @Inject()
    getFileExtension: GetFileExtension;
    minioClient = new Minio.Client({
        endPoint: config.minioConfig.intranetPath,
        port: config.minioConfig.port,
        useSSL: config.minioConfig.useSSL,
        accessKey: config.minioConfig.accessKey,
        secretKey: config.minioConfig.secretKey,
    });
    bucket = config.minioConfig.bucket;
    async minioUpload(files: Array<UploadFileInfo>, name: string = ''): Promise<string> {
        try {
            const originalFilename = this.getFileExtension.getFileExtension(files);
            let filename: string;
            if (name) {
                filename = name + '.' + originalFilename;
            } else {
                filename = uuidv7() + '.' + originalFilename;
            }
            await this.minioClient.fPutObject(this.bucket, filename, files[0].data)
            const url = `https://${config.minioConfig.endPoint}/${this.bucket}/${filename}`;
            return url;
        } catch (error) {
            throw new Error('上传失败');
        }
    }
}